package com.sinovate.liteEMS.web.controller;

import java.util.Collection;
import java.util.logging.Logger;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.sinovate.liteEMS.Constants;
import com.sinovate.liteEMS.session.dao.MySqlSessionDAO;

@RequiresPermissions("session:*")
@Controller
@RequestMapping("/sessions")
public class SessionController {

	@Autowired
	private MySqlSessionDAO sessionDAO;

	@RequestMapping()
	public String list(Model model) {
		Collection<Session> sessions = sessionDAO.getActiveSessions();
//		Logger.getGlobal().info("sessions: "+sessions.toString());
		model.addAttribute("sessions", sessions);
		model.addAttribute("sessionCount", sessions.size());
		return "sessions/list";
	}

	@RequestMapping("/{sessionId}/forceLogout")
	public String forceLogout(@PathVariable("sessionId") String sessionId,
			RedirectAttributes redirectAttributes) {
		String msg = "force logout failed";
		try {
			Session session = sessionDAO.readSession(sessionId);
			if (session != null) {
				session.setAttribute(Constants.SESSION_FORCE_LOGOUT_KEY,
						Boolean.TRUE);
//				session.setAttribute(Constants.SESSION_FORCE_LOGOUT_KEY,
//						Constants.SESSION_FORCE_LOGOUT_KEY);
//				sessionDAO.delete(session);
//				sessionDAO.uncache(session);
				sessionDAO.update(session);
				sessionDAO.doDelete(session);
				Logger.getAnonymousLogger().info("sid: "+session.getId().toString());
				msg = "force logout success!";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		redirectAttributes.addFlashAttribute("msg", msg);
		return "redirect:/sessions";
	}

}
